package com.jbjr.tianchi.service;

import com.jbjr.tianchi.Parments.AggregationBuildersParment;
import com.jbjr.tianchi.Parments.QueryEs;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @Author：zgh
 * @DATE: 2018/7/31 15:11
 * @version: 0.0.1
 * @Description:
 */
@Service
public class QueryEsService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private SearchSourceBuilderHandle searchSourceBuilderHandle;


    /**
     * 查询方法
     * @param param
     * @return
     */
    public Map<String, Object> queryEs(QueryEs param){
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("status","200");
        List<Map<String,Object>> resList = new ArrayList<Map<String,Object>>();

        SearchRequest searchRequest = new SearchRequest(param.getIndex());
        searchRequest.types(param.getType());
        searchRequest.source(searchSourceBuilderHandle.handel(param));
        SearchResponse response = null;
        try{
            response = restHighLevelClient.search(searchRequest);
            SearchHits hits= response.getHits();
            int totalRecordNum= (int) hits.getTotalHits();
            resMap.put("count",totalRecordNum);
            if(totalRecordNum == 0){
                return resMap;
            }

            AggregationBuildersParment Agg = param.getAggregationBuildersParment();
            if(param.getAggregationBuildersParment() != null){
                Aggregations aggregations = response.getAggregations();
                Map <String,Aggregation> aggregationMap = aggregations.getAsMap();
                Terms companyAggregation = (Terms) aggregationMap.get(Agg.getTermsKey());
                List<Terms.Bucket> list = (List<Terms.Bucket>) companyAggregation.getBuckets();

                Map<String,Aggregation> aggregationsResMap = new HashMap<>();
                if(!CollectionUtils.isEmpty(list)){
                    for(int i=0;i<list.size();i++){
                        Terms.Bucket bucket = list.get(i);
                        aggregationsResMap.put(String.valueOf(bucket.getKey()),bucket.getAggregations().get(Agg.getMetricsKey()));
                    }
                }
                resMap.put("aggregationsMap",aggregationsResMap);
            }

            hits.forEach(n -> resList.add(n.getSourceAsMap()));

            resMap.put("resList",resList);
        }  catch (Exception e){
            System.out.println("e:"+e);
        }
        return resMap;
    }



}
